//
//  ZoomableImageView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/7/10.
//

import SwiftUI
import URLImage

struct ZoomableImageView: View {
    let url: String
    @State private var scale: CGFloat = 1.0
    @State private var offset: CGSize = .zero
    @Environment(\.dismiss) var dismiss
    var body: some View {
        GeometryReader { proxy in
            ScrollView([.horizontal, .vertical], showsIndicators: false) {
                URLImage(url: URL(string: url)!) { image in
                    image
                        .resizable()
                        .scaledToFit()
                        .frame(width: proxy.size.width)
                        .scaleEffect(scale)
                        .offset(offset)
                        .gesture(
                            MagnificationGesture()
                                .onChanged { value in
                                    scale = value.magnitude
                                }
                                .onEnded { _ in
                                    if scale < 1 { scale = 1 }
                                }
                        )
                        .gesture(
                            DragGesture()
                                .onChanged { value in
                                    // 只响应垂直方向滑动
                                    if abs(value.translation.width) < abs(value.translation.height) {
                                        offset = value.translation
                                    }
                                }
                                .onEnded { value in
                                    // 下滑超过阈值触发关闭
                                    if value.translation.height > 150 {
                                        dismiss()
                                    } else {
                                        withAnimation(.spring()) {
                                            offset = .zero
                                        }
                                    }
                                }
                        )
                }
            }
        }
    }
}



//#Preview {
//    ZoomableImageView()
//}
